package rabbitmq.topic;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import rabbitmq.constant.Constants;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Producer {
    public static void main(String[] args) throws IOException, TimeoutException {
        //1.建立连接
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(Constants.HOST);
        connectionFactory.setPort(Constants.PORT); //需要提前开放端口号
        connectionFactory.setUsername(Constants.USER_NAME); //账号
        connectionFactory.setPassword(Constants.PASSWORD); //密码
        connectionFactory.setVirtualHost(Constants.VIRTUAL_HOST); //虚拟主机
        Connection connection = connectionFactory.newConnection();
        //2.开启信道
        Channel channel = connection.createChannel();
        //3.声明交换机
        channel.exchangeDeclare(Constants.TOPIC_EXCHANGE, BuiltinExchangeType.TOPIC, true);
        //4.申明队列

        /**
         * queueDeclare(String queue, boolean durable, boolean exclusive, boolean autoDelete,
         *                                                Map<String, Object> arguments)
         * 参数说明:
         * queue:队列名称
         * durable:可持久化 true-设置队列为持久化, 待久化的队列会存盘,服务器重启之后, 消息不丢失。
         * exclusive:是否独占,只能有⼀个消费者监听队列
         * autoDelete:是否⾃动删除, 当没有Consumer时, ⾃动删除掉
         * arguments 参数
         */
        channel.queueDeclare(Constants.TOPIC_QUEUE1, true, false, false, null);
        channel.queueDeclare(Constants.TOPIC_QUEUE2, true, false, false, null);

        //5.交换机和队列绑定
        channel.queueBind(Constants.TOPIC_QUEUE1, Constants.TOPIC_EXCHANGE, "*.a.*");
        channel.queueBind(Constants.TOPIC_QUEUE2, Constants.TOPIC_EXCHANGE, "*.*.b");
        channel.queueBind(Constants.TOPIC_QUEUE2, Constants.TOPIC_EXCHANGE, "c.#");

        //6.发送消息
        /**
         * basicPublish(String exchange, String routingKey, BasicProperties props, byte[] body)
         * 参数说明
         * exchange: 交换机名称, 简单模式下, 交换机会使用默认的""
         * routingKey: 内置交换机, routingKey和队列名称保持一致
         * props: 属性配置
         * body: 消息
         */
        String msg = "hello direct, my routingKey is sae.a.fa ...";
        channel.basicPublish(Constants.TOPIC_EXCHANGE, "sae.a.fa", null, msg.getBytes()); //转发到Q1

        String msg_b = "hello direct, my routingKey is ef.a.b ...";
        channel.basicPublish(Constants.TOPIC_EXCHANGE, "ef.a.b", null, msg_b.getBytes());//转发到Q1,Q2

        String msg_c = "hello direct, my routingKey is c.ef.d ...";
        channel.basicPublish(Constants.TOPIC_EXCHANGE, "c.ef.d", null, msg_c.getBytes());//转发到Q2

        System.out.println("消息发送成功!");

        //6.资源释放
        channel.close();
        connection.close();
    }
}
